﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace project_web2.AdminTool
{
    public partial class ManagerCategories : System.Web.UI.Page
    {
        DAL dal = new DAL();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["Login"] == null) {
                Response.Redirect("Login.aspx");
            }
            grManagerCategories.AllowPaging = true;
            grManagerCategories.PageSize = 5;
            if(!IsPostBack){
                //kien tra session
                LoadGridView();
                
            }  
        }

        private void LoadGridView() {
            grManagerCategories.DataSource = loadInfoCategories();
            grManagerCategories.DataBind();
        }
        private DataTable loadInfoCategories()
        {
            string sql = "select * from Categories";
            return dal.get_data(sql);
        }

        protected void grManagerCategories_RowDataBound(object sender, GridViewRowEventArgs e) {
            if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Alternate || e.Row.RowState == DataControlRowState.Normal)) {
                Button bt = (Button)e.Row.Cells[6].Controls[0];
                bt.OnClientClick = "if(!confirm('Bạn thật sự muốn xóa!')) return false;";
            }
        }

        protected void grManagerCategories_RowCommand(object sender, GridViewCommandEventArgs e) {
            int rowIndex = Convert.ToInt32(e.CommandArgument.ToString());

            if(e.CommandName == "Xoa"){
                int id = Convert.ToInt32(grManagerCategories.DataKeys[rowIndex].Value.ToString());
                deleteRow(id);
                LoadGridView();
            } if (e.CommandName == "Sua") {
                int id = Convert.ToInt32(grManagerCategories.DataKeys[rowIndex].Value.ToString());
                Response.Redirect("AddandEditCategories.aspx?id=" + id);   
            }
        }
        private void deleteRow(int id) {
            string sql = "delete from Categories where categoryid = " + id;
            dal.executeQuery(sql);
        }

        protected void grManagerCategories_PageIndexChanging(object sender, GridViewPageEventArgs e) {
            grManagerCategories.EditIndex = -1;
            grManagerCategories.PageIndex = e.NewPageIndex;
            LoadGridView();
        }

        protected void btnAdd_Click(object sender, EventArgs e) {
            Response.Redirect("AddandEditCategories.aspx");
        }

    }
}